<?php

/**
 * --------------------------------
 * Default BookController
 *
 * 拾光 ysu图书馆系统的书籍相关的统一类  BookController
 *
 * @package 	laravel
 * @subpackage	app/controllers
 * @version 	1.0.0
 * --------------------------------
 */

class BookController extends BaseController {
	//传入view的数据
	public $data = array();
	//是否需要跳转
	public $need_redirect = 0;

	/**
	 * 构造函数
	 *
	 */

	public $goAuth = false;

	public function __construct(){
		session_start();

		$this->data['user_agent'] = $this->getUserAgent();


		if( empty($_SESSION['user_id']) ){
			$this->goAuth = true;
		}


		// //url有token的话，去验证个人信息并重定向去掉token
		// if( Input::has('token') ){
		// 	$current_uri = $_SERVER['REQUEST_URI'];
		//
		// 	$token = Input::get('token');
		// 	$server_url = Config::get('lib.is_dev') ? "http://dev.timepicker.cn/api/user?token=".$token : "http://timepicker.cn/api/user?token=".$token;
		//
		// 	$result = $this->curl_get( $server_url , $token );
		//
		// 	if( !$result || $result == "" ){
		// 		$this->data['check_false'] = 1;
		// 	}
		// 	$user_info_array = json_decode($result , true);
		// 	if( isset( $user_info_array['error'] ) && !$user_info_array['error'] ){
		// 		$user_id 	= $user_info_array['result']['id'];
		// 		$number 	= $user_info_array['result']['school_id'];
		// 		$icon 		= $user_info_array['result']['icon'];
		// 		$name 		= $user_info_array['result']['name'];
		// 		$this->data['user_id'] 	= $user_id;
		// 		$this->data['number'] 	= $number;
		// 		$this->data['icon'] 	= $icon;
		// 		$this->data['token'] 	= $token;
		// 		$this->data['name']		= $name;
		// 		Session::put('token' 	, $token);
		// 		Session::put('user_id' 	, $user_id);
		// 		Session::put('number' 	, $number);
		// 		Session::put('icon' 	, $icon);
		// 		Session::put('token' 	, $token);
		// 		Session::put('name'		, $name);
		// 		Session::put('lib_login', 0);
		//
		// 		$check_user = DB::table('user')->select('id')->where('id','=',$user_id)->get();
		// 		//本系统新用户，添加
		// 		if( count($check_user) == 0 ){
		// 			$insert_arr = array(
		// 				'id' => $user_id ,
		// 				'name' => $name ,
		// 				'number' => $number
		// 			);
		// 			$insert_id = DB::table('user')->insertGetId($insert_arr);
		// 			if( $insert_id < 1 ){
		// 				$this->data['check_false'] = 1;
		// 			}
		// 		}
		//
		// 		$current_uri_arr = explode('?' , $current_uri);
		// 		$current_uri = $current_uri_arr[0];
		// 		$opt_uri = "";
		// 		$opt_uri_arr = array();
		// 		$input_arr = Input::all();
		// 		foreach( $input_arr as $key1 => $val1 ){
		// 			if( $key1 != 'token' ){
		// 				$opt_uri_arr[$key1] = $val1;
		// 				if( $opt_uri != "" ){
		// 					$opt_uri .= '&'.$key1.'='.$val1;
		// 				}else{
		// 					$opt_uri .= $key1.'='.$val1;
		// 				}
		// 			}
		// 		}
		// 		if( $opt_uri != "" ){
		// 			$temp = mt_rand(0,100000000);
		// 			$current_uri .= '?'.$opt_uri."&view=".$temp;
		// 		}
		// 	}else{
		// 		$this->data['check_false'] = 1;
		// 	}
		// 	$this->need_redirect = 1;
		// }else{
		// 	if( Session::has('user_id') ){
		// 		$this->data['user_id'] 	= Session::get('user_id');
		// 		$this->data['icon'] 	= Session::get('icon');
		// 		$this->data['number']   = Session::get('number');
		// 	}else{
		// 		$url = Config::get('lib.auth_uri')."?client_id=".Config::get('lib.client_id')."&redirect_uri=".Config::get('lib.return_uri')."&response_type=token&state=1";
        //         header("Location: $url");
        //         exit;
		// 	}
		// }
	}


	/**
	 * 获取用户图书馆首页的基本信息
	 */
	/**
     * @api {get} /info UserInfo
     * @apiVersion 0.1.0
     * @apiName UserLogin
     * @apiGroup Book
     * @apiPermission app
     *
     * @apiDescription 用户模拟登陆图书馆
     *
     * @apiParam {Number} user_id 用户id.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Object} result 配置数据.
     * @apiSuccess {String} result.name 姓名.
     * @apiSuccess {String} result.over_num 超过人数百分比.
     * @apiSuccess {String} result.level 等级.
     * @apiSuccess {String} result.range 借书范围URL.
     * @apiSuccess {String} result.time 各时间段借书数.
     * @apiSuccess {String} result.five 5天内即将到期书.
     * @apiSuccess {String} result.count 历史总借书册次.
     * @apiSuccess {String} result.own 欠款.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/login
     */
	public function getIndexInfo(){
		include( app_path()."/libraries/Snoopy.class.php");
		include( app_path()."/libraries/simple_html_dom.php");

		if( !Input::has('user_id') )
			return Response::json(['error'=>true , 'message'=>'缺少重要参数'] , 200);
		$user_id = Input::get('user_id');


		$agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36';//伪装浏览器
		$library_ip = "202.206.242.99";
		$library_host = "http://202.206.242.99/";
		$library_pic_router = "reader/redr_info.php";
		$library_referer = "http://202.206.242.99/reader/redr_verify.php";

		$indexInfoUrl = $library_host.$library_pic_router;

		//**
		//获取个人证件信息
		$snoopy = new Snoopy;
		$snoopy->host = $library_ip;
		$snoopy->referer = $library_referer;
		$snoopy->agent = $agent;
		$snoopy->cookies['PHPSESSID'] = Session::get('pre_session');
		$snoopy->fetch($indexInfoUrl);

		$result = $snoopy->results;

		if( $snoopy->timed_out ){
			$this->forgetSession();
			return Response::json( ['error'=>true , 'message'=>'请求超时'] , 200 );
		}

		if( !stripos($snoopy->results,"证件信息") ){
			$this->forgetSession();
			return Response::json( ['error'=>true , 'message'=>'身份信息已失效 , 请重新登录'] , 200 );
		}

		$html = new simple_html_dom();
		$html->load( $result );
		//用户姓名
		$info_name = $html->find(".profile-name")[0]->innertext;

		$info_detail = $html->find(".profile-info-value");
		//证件开始时间
		$info_detail_start_time = $info_detail[0]->children[0]->innertext;
		//证件结束时间
		$info_detail_end_time = $info_detail[1]->children[0]->innertext;
		//email地址
		$info_detail_email = $info_detail[2]->children[0]->innertext;

		$info_data_number = $html->find(".infobox-data-number");

		//超期图书数量
		$info_data_outdate = $info_data_number[0]->innertext;
		//委托到书数量
		$info_data_let = $info_data_number[1]->innertext;
		//预约到书数量
		$info_data_order = $info_data_number[2]->innertext;
		//荐购图书数量
		$info_data_recom = $info_data_number[3]->innertext;

		//超过多少人
		$info_overpeople_num = $html->find(".Num")[0]->innertext;
		//var_dump($info_overpeople_num);

		//获得称号
		$info_level = $html->find("em")[0]->innertext;
		//var_dump($info_level);

		$return_arr = array(
			'name' => $info_name ,
			'over_num' => $info_overpeople_num ,
			'level' => $info_level ,
			'range' => 'http://202.206.242.99/tpl/reader/chartPie.htm' ,
			'time' => 'http://202.206.242.99/tpl/reader/chartColumn.htm',
			);

		//**
		//获取证件信息
		$snoopy2 = new Snoopy;
		$snoopy2->host = $library_ip;
		$snoopy2->referer = "http://202.206.242.99/reader/redr_info.php";
		$snoopy2->agent = $agent;
		$snoopy2->cookies['PHPSESSID'] = Session::get('pre_session');
		$snoopy2->fetch("http://202.206.242.99/reader/redr_info_rule.php");
		$result2 = $snoopy2->results;

		if( $snoopy2->timed_out || !stripos($result2,"证件信息") ){
			$over_to_five = "";
			$all_books_count = "";
			$own_money = "";
		}else{
			$html2 = new simple_html_dom();
			$html2->load($result2);
			$book_nums = $html2->find("strong");

			//五天内即将超期
			$over_to_five = $book_nums[1]->innertext;
			//累计借书
			$all_books_count = $html2->find("td")[12]->innertext;
			//$temp_pos = stripos($all_books_count,"</span>");
			$all_books_count_arr = explode("</span>", $all_books_count);
			$all_books_count = $all_books_count_arr[1];
			$all_books_count = substr(trim($all_books_count) , 0 , 2);
			//欠款金额
			$own_money = $html2->find("td")[14]->innertext;
			// $temp_pos = stripos($own_money,"</span>");
			// $own_money = substr($own_money[1] , $temp_pos+7);
			$own_money_arr = explode("</span>", $own_money);
			$own_money = $own_money_arr[1];
		}
		$return_arr['five'] = $over_to_five;
		$return_arr['count'] = $all_books_count;
		$return_arr['own'] = $own_money;
		DB::table('user')->where('id','=',$user_id)->update($return_arr);


		//**
		// 获取分人的rss令牌
		// 先判断是否已存在rss令牌
		$rss_token = "";
		//$target_rss_exit = DB::table('user')->where('id','=',$user_id)->get();

		//if( count($target_rss_exit) == 0 || $target_rss_exit[0]->rss == "" || $target_rss_exit[0]->rss == null ){
			$snoopy3 = new Snoopy;
			$snoopy3->host = $library_ip;
			$snoopy3->agent = $agent;
			$snoopy3->cookies['PHPSESSID'] = Session::get('pre_session');
			$snoopy3->fetch("http://202.206.242.99/reader/redr_cust_result.php");
			$result3 = $snoopy3->results;
			if( !$snoopy3->timed_out ){
				$temp_pos1 = strpos($result3 , "http://202.206.242.99:80/reader/rss.php?type=3&id=");
				//DB::table('user')->where('id','=',$user_id)->update( array('rss'=>$result3) );
				if( $temp_pos1 ){
					$target_url_string = substr($result3 , $temp_pos1+50 , 48);
					DB::table('user')->where('id','=',$user_id)->update( array('rss'=>$target_url_string) );
					$rss_token = $target_url_string;
				}
			}
		//}else{
		//	$rss_token = $target_rss_exit[0]->rss;
		//}

		//超期图书本数
		$temp_counter = 0;
		if( $rss_token != "" ){
			//直接请求rss接口
			$rss_url = "http://202.206.242.99/reader/rss.php?type=3&id=".$rss_token;
			//设置编码为UTF-8
			$fp = fopen($rss_url , "r") or die("can not open $rss_url");
			$buff = "";
			while ( !feof($fp) ) {
		        $buff .= fgets($fp,4096);
		    }
		    //关闭文件打开
		    fclose($fp);
		    //建立一个 XML 解析器
    		$parser = xml_parser_create();
    		//xml_parser_set_option -- 为指定 XML 解析进行选项设置
		    xml_parser_set_option($parser , XML_OPTION_SKIP_WHITE , 1);
		    //xml_parse_into_struct -- 将 XML 数据解析到数组$values中
		    xml_parse_into_struct($parser , $buff , $values , $idx);
		    //xml_parser_free -- 释放指定的 XML 解析器
		    xml_parser_free($parser);
		    //header("Content-type:text/html;charset=utf-8");
		    //$values = mb_convert_encoding($values , "UTF-8//IGNORE" , "GB2312");
		    $is_item = -1;
		    $temp_counter = 0;
		    foreach( $values as $val ){
		    	$tag = $val['tag'];
		    	$type = $val['type'];
		    	//$value = $val['value'];
		    	//标签统一转为小写
        		$tag = strtolower($tag);
        		if( $tag == 'item' && $type == 'open' ){
        			$is_item = 1;
        		}else if( $tag == 'item' && $type == 'close' ){
        			$is_item = 0;
        		}
        		if( $is_item == 1 ){
        			if( $tag == 'title' ){
        				$temp_counter++;
        			}
        		}
		    }
		}

		return Response::json(['error'=>false , 'result'=>$return_arr , 'rss'=>$temp_counter ] , 200);
	}





	/**
     * @api {get} /search_history UserHistory
     * @apiVersion 0.1.0
     * @apiName UserHistory
     * @apiGroup Book
     * @apiPermission app
     *
     * @apiDescription 获取用户搜索历史
     *
     * @apiParam {Number} user_id 用户id.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Object} result 配置数据.
     * @apiSuccess {String} result.user_id 用户id.
     * @apiSuccess {String} result.content 搜索内容.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/search_history
     */
	public function getSearchHistory(){
		if( !Input::has('user_id') )
			return Response::json(['error'=>true , 'message'=>'缺少重要参数'] , 200);

		$user_id = Input::get('user_id');
		$target_result = DB::table('user_search_history')
							->select('*')
							->orderBy('add_time' , 'DESC')
							->limit(10)
							->get();

		return Response::json(['error'=>false , 'result'=>$target_result] , 200);
	}



	/**
     * @api {get} /search BookSearch
     * @apiVersion 0.1.0
     * @apiName BookSearch
     * @apiGroup Book
     * @apiPermission app
     *
     * @apiDescription 用户搜索书籍
     *
     * @apiParam {Number} user_id 用户id
     * @apiParam {Number} page 页数.
     * @apiParam {String} content 搜索内容.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Object} result 配置数据.
     * @apiSuccess {String} result.name 书名.
     * @apiSuccess {String} result.index 图书馆索引号.
     * @apiSuccess {String} result.href 详情连接.
     * @apiSuccess {String} result.author 作者.
     * @apiSuccess {String} result.press 出版社.
     * @apiSuccess {String} result.type 书籍类型.
     * @apiSuccess {String} result.collect 馆藏复本.
     * @apiSuccess {String} result.rent 可借复本.
     * @apiSuccess {String} message 提示消息.
     * @apiSuccess {Object} page 分页数据.
     * @apiSuccess {Number} current 当前页.
     * @apiSuccess {Number} all 总页数.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/history
     */
	public function searchBook(){

		if( empty($_SESSION['user_id']) ){
			$state          = urlencode( Config::get("lib.app_url").'/search' );
			if( !Input::has('content') || strlen(Input::get('content')) == 0 ){
				$state      = urlencode( Config::get("lib.app_url").'/search?content='.Input::get('content') );
			}
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return Redirect::to($redirectUrl);
        }

		$this->data['description'] = "搜索图书列表";

		if( !Input::has('content') || strlen(Input::get('content')) == 0 ){
			$this->data['search_error'] = 1;
			$this->data['search_error_msg'] = "搜索内容不能为空";
		}

		$content 	= Input::get('content');
		$page 		= Input::has('page') ? Input::get('page') : 1;
		$button 	= Input::get('button');

		$this->data['content'] = rawurldecode($content);

		$user_id = $_SESSION['user_id'];
		$arr = array(
			'method' => 'POST' ,
			'path' => 'book/search' ,
			'query' => array(
				'content' => $content ,
				'page' => $page
				) ,
			'notoken' => 1
			);
		$uri = Config::get('lib.ptime_api')."/user/".$user_id."/campus/1/system/3/api";
		$verify = $this->curl_post( $uri , $arr , "campus" , "" );
		$verify_result = json_decode($verify , true);

		if( isset($verify_result['error']) ){
			if( $verify_result['error'] ){
				if( $verify_result['result'] == 'tokenNull' || $verify_result['result'] == 'tokenTimeOut' ){
					$back_uri = Config::get('lib.app_url')."/search?content=".$content."&page=".$page;
					$auth_uri = Config::get('lib.campus_uri')."/auth?state=".urlencode($back_uri)."&user_id=".$user_id."&system_cat=library";
					return Redirect::to($auth_uri);
				}else{
					return Redirect::to(Config::get('lib.app_url'));
				}
			}else{
				$this->data['search_result'] 	= $verify_result['result']['result'];
				$this->data['page'] = $verify_result['result']['page'];
				return View::make('search_list' , $this->data);
			}
		}else{
			return Redirect::to(Config::get('lib.app_url'));
		}

		// if( $button == 1 ){
		// 	//插入搜索记录
		// 	$target_result = DB::table('user_search_history')->select('*')->where('user_id','=',$user_id)->get();
		// 	if( $user_id > 0 ){
		// 		if( count($target_result) >= 10 ){
		// 			$target_delete = DB::table('user_search_history')
		// 								->where('user_id','=',$user_id)
		// 								->orderBy('add_time' , 'ASC')
		// 								->skip(0)
		// 								->take(count($target_result)-9)
		// 								->delete();
		// 		}
		// 	}
		// 	$insert_arr = array(
		// 		'user_id' => $user_id ,
		// 		'content' => $content
		// 		);
		// 	DB::table('user_search_history')->insertGetId($insert_arr);
		// }
	}



	function searchBookApi(){
		if( !Input::has('content') || strlen(Input::get('content')) == 0 ){
			return Response::json(['error'=>true , 'message'=>'搜索内容不能为空'] , 200);
		}

		$content 	= Input::get('content');
		$page 		= Input::has('page') ? Input::get('page') : 1;

		if( empty($_SESSION['user_id']) ){
			return Response::json(['error'=>true , 'message'=>'请先登录'] , 200);
		}
		$user_id = $_SESSION['user_id'];

		$arr = array(
			'method' => 'POST' ,
			'path' => 'book/search' ,
			'query' => array(
				'content' => $content ,
				'page' => $page
				) ,
			'notoken' => 1
			);
		$uri = Config::get('lib.ptime_api')."/user/".$user_id."/campus/1/system/3/api";
		$verify = $this->curl_post( $uri , $arr , "campus" , "" );
		$verify_result = json_decode($verify , true);

		if( isset($verify_result['error']) ){
			if( $verify_result['error'] ){
				return Response::json(['error'=>true , 'message'=>'搜索出错'] , 200);
			}else{
				return Response::json(['error'=>false , 'result'=>$verify_result['result']['result'] , 'page'=>$verify_result['result']['page'] ,  'message'=>'搜索成功'] , 200);
			}
		}else{
			return Response::json(['error'=>true , 'message'=>'搜索出错'] , 200);
		}
	}



	/**
     * @api {get} /detail BookDetail
     * @apiVersion 0.1.0
     * @apiName BookDetail
     * @apiGroup Book
     * @apiPermission app
     *
     * @apiDescription 书籍详情
     *
     * @apiParam {String} href 详情链接.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Object} table 可借阅信息.
     * @apiSuccess {String} table.index 索引号.
     * @apiSuccess {String} table.num 条码号.
     * @apiSuccess {String} table.href 年份.
     * @apiSuccess {String} table.location 位置.
     * @apiSuccess {String} table.state 状态.
     * @apiSuccess {Object} list 详情列表.
     * @apiSuccess {String} list.title 书名.
     * @apiSuccess {String} list.press 出版社.
     * @apiSuccess {String} list.author 责任者.
     * @apiSuccess {String} list.brief 摘要.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/history
     */
	public function bookDetail(){

		if( !Input::has('href') || strlen(Input::get('href')) <= 0 ){
			$this->data['detail_error'] = 1;
			$this->data['detail_error_msg'] = '目标图书不能为空';
		}
		$href = Input::get('href');

		if( empty($_SESSION['user_id']) ){
			$state          = urlencode( Config::get("lib.app_url")."/detail?href=".$href );
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return Redirect::to($redirectUrl);
        }

		$mac_no = "";
		$href_arr = explode('=' , $href);
		if( count($href_arr) < 2 ){
			$this->data['detail_error'] = 1;
			$this->data['detail_error_msg'] = '目标图书记录号错误';
		}else{
			$mac_no = $href_arr[1];
		}

		$user_id = $_SESSION['user_id'];
		$this->data['user_id'] = $user_id;
		$arr = array(
			'method' => 'POST' ,
			'path' => 'book/detail' ,
			'query' => array(
				'href' => "item.php?marc_no=".$mac_no ,
				),
			'notoken' => 1
			);

		$uri = Config::get('lib.ptime_api')."/user/".$user_id."/campus/1/system/3/api";
		$verify = $this->curl_post( $uri , $arr , "campus" , "" );
		$verify_result = json_decode($verify , true);

		if( isset($verify_result['error']) ){
			if( $verify_result['error'] ){
				if( $verify_result['result'] == 'tokenNull' || $verify_result['result'] == 'tokenTimeOut' ){
					$back_uri = Config::get('lib.app_url')."/detail?href=item.php?marc_no=".$mac_no;
					$auth_uri = Config::get('lib.campus_uri')."/auth?state=".urlencode($back_uri)."&user_id=".$user_id."&system_cat=library";
					return Redirect::to($auth_uri);
				}
			}else{
				//查找是否已收藏
				$temp_no = $mac_no;
				$temp_no_length = strlen($temp_no);
				$temp_no_attach = "";
				if( $temp_no_length < 10 ){
					$split = 10 - $temp_no_length;
					for( $i=1 ; $i<=$split ; $i++ ){
						$temp_no_attach .= '0';
					}
					$temp_no = $temp_no_attach.$temp_no;
				}
				$mac_no = $temp_no;

				$collect_query = DB::table('user_collection')->where('user_id','=',$user_id)->where('mac_no','=',$mac_no)->get();
				if( count($collect_query) > 0 ){
					$verify_result['is_collect'] = 1;
				}else{
					$verify_result['is_collect'] = 0;
				}
				foreach( $verify_result['result'] as $key => $val ){
					$this->data[$key] = $val;
				}
				$this->data['is_collect'] = $verify_result['is_collect'];
				return View::make('search_detail' , $this->data);
			}
		}else{
			$back_uri = Config::get('lib.app_url')."/detail?href=".$mac_no;
			$auth_uri = Config::get('lib.campus_uri')."/auth?state=".urlencode($back_uri)."&user_id=".$user_id."&system_cat=library";
			return Redirect::to($auth_uri);
		}
	}



	// (ajax)
	//书籍相关借阅或者
	public function relatedData(){

		if( !Input::has('url') || !Input::has('type') || !Input::has('call_no') ){
			return Response::json(['error'=>true , 'message'=>'缺少参数信息'] , 200);
		}

		$user_id = $_SESSION['user_id'];
		$arr = array(
			'method' => 'POST' ,
			'path' => 'book/related' ,
			'query' => array(
				'url' => Input::get('url') ,
				'type' => Input::get('type') ,
				'call_no' => Input::has('call_no')
				)
			);
		$uri = Config::get('lib.ptime_api')."/user/".$user_id."/system_cat/library/api";
		$verify = $this->curl_post( $uri , $arr , "campus" , "" );
		$verify_result = json_decode($verify , true);

		if( isset($verify_result['error']) ){
			if( $verify_result['error'] ){
				if( $verify_result['result'] == 'tokenNull' || $verify_result['result'] == 'tokenTimeOut' ){
					return Response::json(['error'=>true , 'result'=>[] , 'message'=>'请求失败1'] , 200);
				}
			}else{
				return Response::json(['error'=>false , 'result' => $verify_result['result'] , 'message'=>''] , 200);
			}
		}else{
			return Response::json(['error'=>true , 'result'=>[] , 'message'=>'请求失败2'] , 200);
		}
	}



	/**
     * @api {get} /current BookCurrent
     * @apiVersion 0.1.0
     * @apiName BookCurrent
     * @apiGroup Book
     * @apiPermission app
     *
     * @apiDescription 获取当前所借书籍
     *
     * @apiParam {Number} user_id 用户id.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Object} result 配置数据.
     * @apiSuccess {String} result.num 条码号.
     * @apiSuccess {String} result.name 书名.
     * @apiSuccess {String} result.location 位置.
     * @apiSuccess {String} result.con_num 续借数量.
     * @apiSuccess {String} result.attach 附件.
     * @apiSuccess {String} result.rent_time 借阅时间.
     * @apiSuccess {String} result.return_time 归还时间.
     * @apiSuccess {String} result.renew_code 续借码2.
     * @apiSuccess {String} result.bar_code 续借码1.
     * @apiSuccess {Number} result.state 此书的状态  0正常 1超期.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/current
     */
	public function currentRent(){
		include( app_path()."/libraries/Snoopy.class.php");
		include( app_path()."/libraries/simple_html_dom.php");

		$agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36';//伪装浏览器
		$library_ip = "202.206.242.99";
		$library_referer = "http://202.206.242.99/reader/book_lst.php";

		$snoopy2 = new Snoopy;
		$snoopy2->host = $library_ip;
		$snoopy2->referer = $library_referer;
		$snoopy2->agent = $agent;
		$snoopy2->cookies['PHPSESSID'] = Session::get('pre_session');

		$target_url = "http://202.206.242.99/reader/book_lst.php";
		$snoopy2->fetch($target_url);

		$result = $snoopy2->results;

		if( $snoopy2->timed_out || !strpos($result , "当前借阅") ){
			$this->forgetSession();
			return Response::json( ['error'=>true , 'message'=>'请求超时'], 200);
		}

		$html = new simple_html_dom();
		$html->load($result);

		//获取所有在借书籍
		$current_rent_arr = array();

		$table_line = $html->find(".table_line")[0];
		$table_line_count = count($table_line);

		$all_trs = $table_line->find("tr");

		for( $i=1 ; $i < count($all_trs) ; $i++ ){
			$temp_tr = $all_trs[$i];
			$temp_tds = $temp_tr->find("td");

			//分析详情连接
			$temp_as = $temp_tds[1]->find("a");
			if( count($temp_as) > 0 ){
				$temp_as_href = $temp_as[0]->href;
				$target_detail_url = substr($temp_as_href , 8);
			}else{
				$target_detail_url = "";
			}

			//分析此借阅书的状态
			$book_state = "0";
			$temp_return = $temp_tds[3];
			$temp_font = $temp_return->find("font")[0]->color;
			if( $temp_font == 'red' ){
				$book_state = 1;
			}

			$renew_input = $temp_tr->find("input");
			if( count($renew_input) == 0 ){
				$temp_renew_code = "";
				$bar_code = "";
			}else{
				$getLib = $renew_input[0]->onclick;
				$checkCode_arr = explode(",", $getLib);
				$bar_code = substr($checkCode_arr[0] , 10 , 7);
				$checkCode = substr($checkCode_arr[1] , 1 , 8);
				$temp_renew_code = $checkCode;
			}
			$current_rent_arr[] = array(
				'num' => $temp_tds[0]->innertext ,
				'name' => $temp_tds[1]->innertext ,
				'href' => $target_detail_url ,
				'rent_time' => trim($temp_tds[2]->innertext) ,
				'return_time' => trim($temp_tds[3]->innertext) ,
				'con_num' => $temp_tds[4]->innertext ,
				'location' => $temp_tds[5]->innertext ,
				'attach' => $temp_tds[6]->innertext ,
				'renew_code' => $temp_renew_code ,
				'bar_code' => $bar_code ,
				'state' => $book_state
				);
		}

		return Response::json( ['error'=>false , 'result'=>$current_rent_arr] , 200 );
	}



	/**
     * @api {get} /renew_pic BookRenewPic
     * @apiVersion 0.1.0
     * @apiName BookRenewPic
     * @apiGroup Book
     * @apiPermission app
     *
     * @apiDescription 获取续借验证码
     *
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {String} pic 验证码图片base64.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/detail
     */
	public function reRentPic(){
		include( app_path()."/libraries/Snoopy.class.php");
		ini_set("max_execution_time" , 18000);

		$agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36';//伪装浏览器
		$library_ip = "202.206.242.99";
		$library_host = "http://202.206.242.99/";
		$library_pic_router = "reader/captcha.php";

		$snoopy = new Snoopy;
		$submit_url = $library_host.$library_pic_router;

		$snoopy->host = $library_ip;
		$snoopy->agent = $agent;
		$snoopy->referer = "http://202.206.242.99/reader/book_lst.php";
		$snoopy->cookies['PHPSESSID'] = Session::get('pre_session');
		$snoopy->fetch($submit_url);

		//超时返回
		if ($snoopy->status != '200' || $snoopy->timed_out)
	    	return Response::json( ['error'=>true , 'message'=>'获取验证码失败'] , 200 );

		$result = $snoopy->results;
		$pic_data = "data:image/gif;base64,".base64_encode($result);

		return Response::json( ['error'=>false , 'pic'=>$pic_data] , 200 );
	}




	/**
     * @api {get} /renew BookRenew
     * @apiVersion 0.1.0
     * @apiName BookRenew
     * @apiGroup Book
     * @apiPermission app
     *
     * @apiDescription 续借书籍
     *
     * @apiParam {String} bar_code 续借码1.
     * @apiParam {String} check 续借码2.
     * @apiParam {String} captcha 验证码.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/renew
     */
	public function renew(){
		include( app_path()."/libraries/Snoopy.class.php");

		if( !Input::has('bar_code') || !Input::has('check') || !Input::has('captcha') )
			return Response::json( ['error'=>false , 'pic'=>$pic_data] , 200 );

		$bar_code 	= Input::get('bar_code');
		$check 		= Input::get('check');
		$captcha 	= Input::get('captcha');
		$time = time();

		$agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36';		//伪装浏览器
		$library_ip = "202.206.242.99";
		$library_host = "http://202.206.242.99/";
		$library_renew_router = "reader/ajax_renew.php";

		$snoopy = new Snoopy;
		$renew_url = $library_host.$library_renew_router;
		$renew_url .= "?bar_code=".$bar_code;
		$renew_url .= "&check=".$check;
		$renew_url .= "&captcha=".$captcha;
		$renew_url .= "&time=".$time;

		$snoopy->host = $library_ip;
		$snoopy->agent = $agent;
		$snoopy->cookies['PHPSESSID'] = Session::get('pre_session');
		$snoopy->fetch($renew_url);

		//超时返回
		if ($snoopy->status != '200' || $snoopy->timed_out)
	    	return Response::json( ['error'=>true , 'message'=>'续借失败'] , 200 );

		$result = $snoopy->results;

		return Response::json( ['error'=>false , 'message'=>$result] , 200 );
	}



	/**
     * @api {get} /history BookRentHistory
     * @apiVersion 0.1.0
     * @apiName BookRentHistory
     * @apiGroup Book
     * @apiPermission app
     *
     * @apiDescription 借书历史
     *
     * @apiParam {Number} page 页数.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Object} result 配置数据.
     * @apiSuccess {String} result.num 条码.
     * @apiSuccess {String} result.title 书名.
     * @apiSuccess {String} result.author 作者.
     * @apiSuccess {String} result.rent_time 借阅时间.
     * @apiSuccess {String} result.return_time 归还时间.
     * @apiSuccess {String} result.location 书籍位置.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/history
     */
	public function rentHistory(){
		include( app_path()."/libraries/Snoopy.class.php");
		include( app_path()."/libraries/simple_html_dom.php");

		if( !Input::has('page') || Input::get('page') <= 0 )
			return Response::json( ['error'=>true , 'message'=>'传入页码出错'] , 200 );
		$page = Input::get('page');

		$agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36';//伪装浏览器
		$library_ip = "202.206.242.99";
		$library_host = "http://202.206.242.99/";
		$library_hist_router = "reader/book_hist.php";

		$snoopy = new Snoopy;
		$hist_url = "http://202.206.242.99/reader/book_hist.php";
		$hist_url .= "?page=".$page;

		$snoopy->host = $library_ip;
		$snoopy->agent = $agent;
		$snoopy->cookies['PHPSESSID'] = Session::get('pre_session');
		$snoopy->fetch($hist_url);

		//超时返回
		if ($snoopy->status != '200' || $snoopy->timed_out){
			$this->forgetSession();
	    	return Response::json( ['error'=>true , 'message'=>'请求超时'] , 200 );
		}

	    $result = $snoopy->results;

	    $html = new simple_html_dom();
	    $html->load($result);

	    $hist_arr = array();
	    $table_line = $html->find(".table_line")[0];
	    $all_trs = $table_line->find("tr");

	    for( $i=1 ; $i<count($all_trs) ; $i++ ){
	    	$temp_tr = $all_trs[$i];
	    	$all_tds = $temp_tr->find("td");
	    	//分析详情连接
			$temp_as = $all_tds[2]->find("a");
			if( count($temp_as) > 0 ){
				$temp_as_href = $temp_as[0]->href;
				$target_detail_url = substr($temp_as_href , 8);
			}else{
				$target_detail_url = "";
			}
	    	//条码
	    	$num = $all_tds[1]->innertext;
	    	//标题
	    	$title = $all_tds[2]->innertext;
	    	//作者
	    	$author = $all_tds[3]->innertext;
	    	//借阅日期
	    	$rent_time = $all_tds[4]->innertext;
	    	//归还日期
	    	$return_time = $all_tds[5]->innertext;
	    	//馆藏地
	    	$location = $all_tds[6]->innertext;

	    	$hist_arr[] = array(
	    		'num' => $num ,
	    		'href' => $target_detail_url ,
	    		'title' => $title ,
	    		'author' => $author ,
	    		'rent_time' => $rent_time ,
	    		'return_time' => $return_time ,
	    		'location' => $location
	    		);
	    }

	    //查找分页数据
	    $all_pages = $html->find("#f")[0];
	    $all_fonts = $all_pages->find("font");
	    $page_arr = array(
	    	'current' => $all_fonts[0]->innertext ,
	    	'all' => $all_fonts[1]->innertext
	    	);

	    return Response::json( ['error'=>false , 'result'=>$hist_arr , 'page'=>$page_arr] , 200 );
	}



	/**
     * @api {post} /search_history BookAddHistory
     * @apiVersion 0.1.0
     * @apiName BookAddHistory
     * @apiGroup Book
     * @apiPermission app
     *
     * @apiDescription 添加搜索记录
     *
     * @apiParam {String} content 搜索内容.
     * @apiParam {Number} user_id 用户id.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://192.168.1.179:82/search_history
     */
	public function addSearchHistory(){
		if( !Input::has('content') || !Input::has('user_id') )
			return Response::json( ['error'=>true , 'message'=>'缺少重要参数'] , 200 );
		$content = Input::get('content');
		$user_id = Input::get('user_id');

		$target_result = DB::table('user_search_history')
							->select('*')
							->where('user_id','=',$user_id)
							->get();
		if( count($target_result) > 10 ){
			$target_delete = DB::table('user_search_history')
								->where('user_id','=',$user_id)
								->orderBy('add_time' , 'ASC')
								->limit(count($target_result)-9)
								->delete();
		}

		$insert_arr = array(
			'user_id' => $user_id ,
			'content' => $content
			);

		$target_insert_id = DB::table('user_search_history')->insertGetId($insert_arr);

		if( $target_insert_id > 0 )
			return Response::json( ['error'=>false , 'message'=>'插入成功'] , 200 );
		else
			return Response::json( ['error'=>true , 'message'=>'插入失败'] , 200 );

	}


	//删除session
	public function forgetSession(){
		Session::forget('user_id');
		Session::forget('number');
		Session::forget('password');
	}


	//供每日的轮询调用
	public function checkUserBook(){
		//设置不超时
		set_time_limit(0);
		$allUsers = DB::table('user')->select('id','number','rss')->get();
		foreach ($allUsers as $key => $value) {
			$user_id 	= $value->id;
			$rss 		= $value->rss;
			if( $rss != "" && strlen($rss) > 0 ){
				Queue::push('CheckBookRss@app' , ["user_id"=>$user_id,"rss"=>$rss]);
			}
		}
		return Response::json( ['error'=>false , 'result'=>count($allUsers)] , 200 );
	}


	public function getUserAgent(){
        if( strpos($_SERVER['HTTP_USER_AGENT'], 'PTime.IOSWeb') !== false):
            $userAgent = "ptimeios";
        elseif( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false):
            $userAgent = "wechat";
        elseif( strpos($_SERVER['HTTP_USER_AGENT'], 'PTime.AndroidWeb') !== false):
            $userAgent = "ptimeandroid";
        elseif( strpos($_SERVER['HTTP_USER_AGENT'], 'MQQBrowser')!== false):
            $userAgent = "mqq";
        else:
            $userAgent = "other";
        endif;
        return $userAgent;
    }

}
